<script>
import ReportPerson from '@/components/quarterly-account-table/report-person.vue'
import TableHead from '@/components/quarterly-account-table/table-head.vue'
import {
  TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
} from '@/config'
import {
  loadEquipmentStatus,
} from '@/api/enterpriseQuarterlyReport'
import { selectEnergyDiscountList } from '@/api/energyDiscount'
import { uuid } from '@/utils'
import EnergyTableMixin from '@/components/quarterly-account-table/energy-table-mixin'

export default {
  name: 'condition-table-of-major-energy-consuming-equipment',
  mixins: [EnergyTableMixin],
  components: {
    TableHead,
    ReportPerson
  },
  props: {
    // 企业ID
    enterpriseId: {
      type: String,
      required: true,
    },
    // 企业名称
    enterpriseName: String,
    // 年份
    year: {
      type: [String, Number],
      required: true,
    },
    // 季度
    quarter: {
      type: [String, Number],
      required: true,
    },
    // 表ID
    tId: {
      type: Number,
      required: true,
    },
    // 表名称
    name: {
      type: String,
      required: true,
    },
    // 表数据项
    columns: {
      type: Array,
      required: true,
    },
    // 政府端
    isGovernment: Boolean,
    readonly: Boolean,
    showLineNumber: {
      type: Boolean,
      default: true,
    }
  },
  data () {
    return {
      // 点击单元格后，正在输入的input索引
      inputIndex: -1,
      /**
       * 报表数据格式
       * [{uuid: string, data: string[]}]
       */
      lists: [],
    }
  },
  computed: {
    title () {
      // 年度
      if (Number(this.quarter) === 5) {
        return `${this.enterpriseName || ''}（${this.year}年）${this.name}`
      }
      if (this.enterpriseName) {
        return `${this.enterpriseName}（${this.year}年第${this.quarter}季度）${this.name}`
      }
      return `${this.name}（${this.year}年第${this.quarter}季度）`
    },
    fromGovernmentSide () {
      return this.isGovernment && this.readonly === true
    },
    // 多级表头转一级表头
    flattenColumns () {
      const columns = this.columns
      const getItems = (arr) => {
        const result = [];
        (function callback (arr) {
          for (let i = 0; i < arr.length; i++) {
            const { children, ...rest } = arr[i]
            if (children && children.length > 0) {
              callback(children)
            } else {
              result.push({ ...rest })
            }
          }
        })(arr)
        return result
      }
      return getItems(columns)
    },
  },
  methods: {
    loadList () {
      return loadEquipmentStatus
    },
    getEnergyDiscount () {
      return selectEnergyDiscountList().then(res => {
        return res.data || []
      })
    },
    getPrevLists (params) {
      return this.initLists(params)
    },
    refresh () {
      this.initLists()
    },
    _initLists (l, min) {
      min = min || 2
      if (l < min) {
        const columns = this.flattenColumns
        const rest = Array(min - l).fill(1).map(() => ({
          uuid: uuid(),
          data: Array(columns.length).fill('')
        }))
        this.lists = this.lists.concat(rest)
      }
    },
    // 初始化表数据
    initLists (params) {
      const props = this.flattenColumns.map(v => v.prop)

      const transfer = (obj) => {
        return props.map(prop => String(obj[prop] || ''))
      }
      // 查询企业填报的数据
      if (this.loadList) {
        params = params || {
          [TABLE_FIELD_YEAR]: this.year,
          [TABLE_FIELD_QUARTER]: this.quarter,
          tenantId: this.enterpriseId
        }
        return this.loadList(params).then(async res => {
          if (res.code === 200) {
            const data = res.data || []
            if (data.length === 0) {
              // 为空时加载默认能源名称
              const energyDiscount = await this.getEnergyDiscount()
              this.lists = energyDiscount.map((v) => ({
                uuid: uuid(),
                data: transfer({
                  energyName: v.name || '',
                  unitOfMeasurement: v.discountFactorUnit ? (v.discountFactorUnit.split('/')[1]) : '吨标准煤',
                  referenceDiscountFactor: v.referenceCoefficient || '',
                  code: String(v.id).padStart(2, '0'),
                })
              }))
            } else {
              this.lists = Array(data.length).fill(1).map((v, i) => ({
                uuid: String(data[i].id),
                data: transfer(data[i])
              }))
            }
            if (!this.fromGovernmentSide) {
              // 补足企业端不足行的数据
              const l = this.lists.length
              this._initLists(l)
            }

            this.$nextTick(() => {
              this.initInputIndex()
            })
          }
        }).catch(() => {
          console.log('reject')
          this._initLists(0)
          this.$nextTick(() => {
            this.initInputIndex()
          })
        })
      }
    },
    // 暴露给使用者的获取报表数据的方法
    // @return [{prop1: string, prop2: string, ...}]
    getData () {
      const props = this.flattenColumns.map(v => v.prop)
      const isNotEmpty = (array) => array.some(v => v !== '')

      // 二维数组 [string[], string[], ...]
      const lists = this.lists.map(v => v.data).filter(v => isNotEmpty(v))
      return lists.map(v => {
        const obj = {}
        props.forEach((prop, index) => {
          obj[prop] = v[index]
        })
        obj[TABLE_FIELD_YEAR] = String(this.year)
        obj[TABLE_FIELD_QUARTER] = String(this.quarter)
        return obj
      })
    },
    // 单击单元格（input框）
    clickHandler (evt) {
      evt.target.select()
      this.inputIndex = Number(evt.target.dataset.inputIndex)
    },
    // 给每个input添加索引
    initInputIndex () {
      const inputs = document.querySelectorAll('.input-cell input')
      inputs.forEach((input, index) => {
        input.dataset.inputIndex = index + ''
      })
    },
  },
}
</script>

<template>
  <div class="bg-white height-100 quarterly-account-table position-relative overflow-hidden">
    <slot name="title" :title="title">
      <h2 class="table-title">
        {{title}}
      </h2>
    </slot>
    <div class="report-table-head">
      <table class="report-table">
        <table-head :columns="columns" :show-line-number="showLineNumber"></table-head>
      </table>
    </div>
    <el-scrollbar :style="{height: 'calc(100% - 130px)'}" wrap-style="overflow-x: hidden;">
      <table class="report-table">
        <tbody ref="tbody">
        <tr v-for="(item, i) in lists" :key="item.uuid">
          <th v-if="showLineNumber" class="readonly width-40px line-number">{{i + 1}}</th>
          <td v-for="(value, index) in item.data" :key="item.uuid + index">
            <div class="input-cell" :class="{'is-readonly': readonly}">
              <input type="text" :readonly="readonly" v-model="item.data[index]" @click="clickHandler">
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <report-person ref="reportPerson" :informer="informant"></report-person>
      <div v-if="tableDescription" class="fill-description">
        <template>
          <!-- <p>说明：</p>
          <p>1．主要逻辑审核关系：</p>
          <p class="padding-horizontal">(1) 消费合计=工业生产消费+非工业生产消费。</p>
          <p class="padding-horizontal">(2) 工业生产消费≥用于原材料。</p>
          <p class="padding-horizontal">(3) 消费合计≥运输工具消费。</p>
          <p>2．企业只填写本企业消耗的有关能源品种数值。如本表未包括企业消耗的能源品种，企业应根据统计部门要求归并入相应能源品种内。</p>
          <p>3．能源合计=∑某种能源×某种能源折标准煤系数（不重复计算“其中”项）。</p>
          <p>4．综合能源消费量的计算方法：</p>
          <p class="padding-horizontal">(1)非能源加工转换企业：综合能源消费量=工业生产消费的能源折标量合计-回收利用折标量合计。</p>
          <p class="padding-horizontal">(2)能源加工转换企业：综合能源消费量=工业生产消费的能源折标量合计-能源加工转换产出折标量合计-回收利用折标量合计。</p> -->
          
          <el-input type="textarea" class="width-100 table-description" :value="tableDescription" readonly autosize></el-input>
        </template>
      </div>
    </el-scrollbar>
  </div>
</template>
